package com.example.taigame;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.example.adapter.ListView_Install_Adapter;

public class ListviewInstalled extends Fragment implements OnItemClickListener{

	private static final String ARG_POSITION = "position";
	private List<PackageInfo> listInfo;
	private ListView_Install_Adapter adapter;
	private static final int ACTIVITY_RESULT = 1000;
	private int position;
	private int clickPosision = 0;
	private ListView g;

	public static ListviewInstalled newInstance(int position) {
		ListviewInstalled f = new ListviewInstalled();
		Bundle b = new Bundle();
		b.putInt(ARG_POSITION, position);
		f.setArguments(b);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		position = getArguments().getInt(ARG_POSITION);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.listview_installed_packed, container, false);
		g = (ListView) view.findViewById(R.id.listView1);
		listInfo = getListApp();
		adapter = new ListView_Install_Adapter(getActivity(),listInfo,getActivity());
		g.setAdapter(adapter);
		g.setOnItemClickListener(this);
		
		return view;
	}
	
	private List<PackageInfo> getListApp(){
		final PackageManager pm = getActivity().getPackageManager();
		List<PackageInfo> packages = pm.getInstalledPackages(0);
		return packages;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		clickPosision = arg2;
		unistallApp(listInfo, arg2);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == ACTIVITY_RESULT && resultCode == 0){
			listInfo = getListApp();
			adapter = new ListView_Install_Adapter(getActivity(),listInfo,getActivity());
			g.setAdapter(adapter);
		}
	}
	
	private void unistallApp(List<PackageInfo> listApp,int position){
		Uri packageURI = Uri.parse("package:"+listApp.get(position).packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE);
		uninstallIntent.setData(packageURI);
		startActivityForResult(uninstallIntent, ACTIVITY_RESULT);
	}
}